package com.ruoyi.recycleshop.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.recycle.domain.ShopManagement;
import com.ruoyi.recycle.dto.LoginDTO;
import com.ruoyi.recycle.exception.BusinessException;
import com.ruoyi.recycle.properties.Wxproperties;
import com.ruoyi.recycle.service.IShopManagementService;
import com.ruoyi.recycle.vo.LoginVO;
import com.ruoyi.recycleshop.service.LoginService;
import com.ruoyi.system.api.RemoteLoginService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.form.LoginBody;
import com.ruoyi.system.api.model.LoginUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private Wxproperties wxproperties;
    @Autowired
    private IShopManagementService shopManagementService;
    @Autowired
    private RemoteLoginService remoteLoginService;
    @Autowired
    private RemoteUserService userService;

    @Override
    public String wechatAuth(String code, String encryptedData, String iv) {
        final String authUrl = StrUtil.indexedFormat(wxproperties.getAuthUrl(), wxproperties.getShopAppId(), wxproperties.getShopSecretKey(), code);
        final String result = HttpUtil.get(authUrl);
        final JSONObject jsonObject = JSONObject.parseObject(result);
        final String openid = jsonObject.getString("openid");
        if (StrUtil.isEmpty(openid)) {
            return jsonObject.getString("errmsg");
        }
        return openid;
    }

    @Override
    @SneakyThrows
    public LoginVO login(LoginDTO loginDTO) {
        final ShopManagement account = shopManagementService.getOne(Wrappers.lambdaQuery(new ShopManagement())
                .eq(ShopManagement::getShopNumber, loginDTO.getUsername()));
        if (Objects.isNull(account)) {
            throw new Exception("找不到该账号");
        }
        if (!StrUtil.equals(account.getStatus(), "1")) {
            throw new BusinessException("账号未被启用,请联系管理人员");
        }
        //if (StrUtil.isEmpty(account.getOpenid())) {
        //      throw new BusinessException(StrUtil.format("无法获取用户openId,请先进行微信授权,以获取用户微信信息"));
        //  }
        // if (StrUtil.isNotEmpty(loginDTO.getOpenId())) {
        //  account.setOpenid(loginDTO.getOpenId());
        // shopManagementService.updateById(account);
        // }
        final R<?> login = remoteLoginService.login(new LoginBody()
                .setUsername(loginDTO.getUsername())
                .setPassword(loginDTO.getPassword()).setIsProgram(true));
        final Map<String, Object> data = (Map<String, Object>) login.getData();
        final R<LoginUser> userInfo = userService.getUserInfo(loginDTO.getUsername(), SecurityConstants.INNER);
        return new LoginVO().setShopManagement(account)
                .setUserInfo((userInfo.getData()))
                .setToken(data.get("access_token"))
                .setExpireTime(data.get("expires_in"));
    }

    @Override
    public R logout(HttpServletRequest request) {
        try {
            return remoteLoginService.logout(request);
        } catch (Exception e) {
            log.error("引流门店用户登出操作产生错误,原因:{}", e.getMessage());
            return R.fail();
        }
    }
}
